package com.poetry.task;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.poetry.domain.dto.PoemDoc;
import com.poetry.domain.po.Poem;
import com.poetry.mapper.PoemMapper;
import com.poetry.util.RedisUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.elasticsearch.core.ElasticsearchOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
public class UpdateDataTask {
    @Resource
    private RedisUtil redisUtil;
    @Resource
    private ElasticsearchOperations elasticsearchOperations;
    @Resource
    private PoemMapper poemMapper;

    @Scheduled(cron = "0 */5 * * * *", zone = "Asia/Shanghai")
    public void updateDoc() {
        LocalDateTime lastTime = redisUtil.getLastSyncTime();
        List<Poem> poems = poemMapper.selectList(new QueryWrapper<Poem>().
                gt("update_time", lastTime).orderByDesc("update_time"));
        List<PoemDoc> poemDocs = new ArrayList<>();
        for (Poem poem : poems) {
            PoemDoc poemDoc = new PoemDoc();
            BeanUtils.copyProperties(poem, poemDoc);
            poemDoc.setCreateTime(new Date());
            poemDoc.populateSuggestions();
            poemDocs.add(poemDoc);
        }
        elasticsearchOperations.save(poemDocs);
        redisUtil.updateSyncTime(LocalDateTime.now());
        log.info("已进行数据库与es的同步工作，同步时间：{}", LocalDateTime.now());
    }
}
